<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2017-7-21
 * Func   注册登录
 */
defined('IN_YuLin') || exit('NO PERMIT!');

if($a == 'logout')
{
    unset($_SESSION['user']);
    unset($_SESSION['uid']);
	unset($_COOKIE['LoginSessionID']);
	set_cookie('LoginSessionID','');

    ShowMsg('退出登录成功',U('member/login'));
}
if($a == 'check')
{
	if(IS_GET)
	{
		$username	=	NoBadStr($_GET['username']);
		$user = $db->getrow('SELECT * FROM '.Table('user').' WHERE username = \''.$username.'\'');
		!$user && AjaxReturn(2,'账号不存在');
	}
}
if($_uid)
{
	header('Location: '.U('member'));
	exit;
}

if(IS_POST)
{
    $username	=	NoBadStr($_POST['username']);
    $password	=	NoBadStr($_POST['password']);
	$code		=	NoBadStr($_POST['validateCode']);
	
	!$username && AjaxReturn(2,'请输入账号');
	!$password && AjaxReturn(2,'请输入密码');
	//!$code && AjaxReturn(2,'请输入验证码');
	
    //include_once LIB_PATH."class/Secoder.class.php";
	//(!Secoder::check($code)) && AjaxReturn(1,'验证码输入不正确');

    $user = $db->getrow('SELECT * FROM '.Table('user').' WHERE username = \''.$username.'\'');
	!$user && AjaxReturn(2,'账号不存在');
	!$user['status'] && AjaxReturn(3,'账号被锁定，请联系管理员');
	($user['password'] != Password($password)) && AjaxReturn(2,'密码错误');
	// 检查邀请码
	$sql  = 'SELECT invita_code_id FROM ' . Table('user_info') . ' WHERE uid = ' . $user['id'];
	$checkInvita = $db->getrow($sql);
	if ($checkInvita['invita_code_id'] <= 0 || !$checkInvita['invita_code_id']) AjaxReturn(3,'账号邀请信息异常，请联系管理员');

	$db->exec('UPDATE '.Table('user').' SET last_time = '.TIMESTAMP.',last_ip = \''.$_Y['ip'].'\' WHERE id = '.$user['id']);
	
	$ins = [];
	$ins['uid'] = $user['id'];
	$ins['ip'] = $_Y['ip'];
	$ins['time'] = TIMESTAMP;
	$db->add('user_loginlog',$ins);

	$_SESSION['userlast'] = $user;
    $_SESSION['uid'] = $user['id'];
	set_cookie('LoginSessionID',session_id());
	
    AjaxReturn(0,'登录成功');
}

$tpl->display('member/login');